<?php

class MatchingHistoryController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                'users' => array('admin'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'generateMatching'),
                'users' => array('admin'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new MatchingHistory;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['MatchingHistory'])) {
            $model->attributes = $_POST['MatchingHistory'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->matching_history_id));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['MatchingHistory'])) {
            $model->attributes = $_POST['MatchingHistory'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->matching_history_id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('MatchingHistory');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new MatchingHistory('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['MatchingHistory']))
            $model->attributes = $_GET['MatchingHistory'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return MatchingHistory the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = MatchingHistory::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param MatchingHistory $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'matching-history-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionGenerateMatching() {
        $model = new MatchingGenerationForm();
        $matchingList = Array();

        if ($_POST) {
            $matchingList = $this->getMatchingList();
            foreach ($matchingList as $mh){
                if($mh->save()){
                    if($mh->earned_amount > 0){
                        $this->saveTransaction($mh);
                    }
                }
            }
            $this->redirect(array('/matchingHistory/admin'));
        } else {
            $matchingList = $this->getMatchingList();            
        }

        $model->matchingList = $matchingList;
        $model->slotList = $this->getMatchingSlotList();
        $this->render('generateMatching', array(
            'model' => $model,
        ));
    }
    
    public function saveTransaction($mh){
        $mt = new MemberTransactionHistory();
        $mt->member_id = $mh->member_id;

        $credit = $mh->earned_amount;
        $cBalance = $this->getCurrentUserBalance($mh->member_id);

        $mt->particulars = "Earned from credit point";
        $mt->debit = 0;
        $mt->credit = $credit;
        $mt->balance = $cBalance + $credit;
        $mt->transaction_date = date("Y-m-d H:i:s");
        $mt->isCreditPointEarning = "1";
        $mt->save();
        
        // flusing member point
        $mb = Member::model()->findByAttributes(array('member_id' => $mh->member_id));
        $mb->a_point = $mh->newAPoint;
        $mb->b_point = $mh->newBPoint;
        $mb->save();
        
                    
    }

    public function getMatchingList() {
        $matchingList = Array();
        $slotList = $this->getMatchingSlotList();
        if ($slotList != NULL) {
            $memberList = $this->getMatchingCalculableMemberList();
            foreach ($memberList as $member) {
                $matching = new MatchingHistory;
                $matching->member_id = $member->member_id;
                $matching->username = $member->username;
                $matching->aPoint = ($member->a_point==NULL)? 0 : $member->a_point;
                $matching->bPoint = ($member->b_point==NULL)? 0 : $member->b_point;
                $matching->matching_slot = $this->getMatchingSlot($matching->aPoint, $matching->bPoint, $slotList); 

                $package = Package::model()->findByAttributes(array('package_id' => $member->package_id));
                $matching->package = $package->name;
                $matching->package_price = $package->price;
                $matching->package_point = $package->point;
                $matching->max_point = $package->matching_limit;
                $matching->earned_amount = $this->getEarningAmount($matching->matching_slot, $matching->max_point); 
                $matching->newAPoint = $this->flushAPoint($matching->aPoint, $matching->bPoint); 
                $matching->newBPoint = $this->flushBPoint($matching->aPoint, $matching->bPoint);; 
                $matching->date = date("Y-m-d H:i:s");

                array_push($matchingList, $matching);
            }
        }
        return $matchingList;
    }
    
    
    public function getMatchingSlot($aPoint, $bPoint, $slotList) {
        $minPoint = 0;
        $slot = NULL;
        try {
            if ($aPoint <= $bPoint) {
                $minPoint = $aPoint;
            } else {
                $minPoint = $bPoint;
            }
            
            $minSlot = $slotList[0];
            $minSlotValue = $minSlot['point'];
            
            $slotsize = sizeof($slotList);
            $maxSlot = $slotList[$slotsize -1];
            $maxSlotValue = $maxSlot['point'];
            
            if($minPoint > $maxSlotValue){
                $slot = $maxSlotValue;
            }
            
            if($minPoint != 0 && $minPoint >= $minSlotValue && $minPoint <= $maxSlotValue){
                
                $prevslot = NULL;
                foreach ($slotList as $s) {
                    if ($minPoint < $s['point']) {
                        $slot = $prevslot;
                        break;
                    }else if($minPoint == $s['point']){
                        $slot = $s['point'];
                        break;
                    }
                    $prevslot = $s['point'];
                }
            }            
        } catch (Exception $e) {
            
        }

        return $slot;
    }
    
    public function getEarningAmount($matchingSlot, $matchingLimit){
        $amount = 0;
        if($matchingSlot != null && $matchingSlot > 0){
            if($matchingSlot < $matchingLimit){
                $amount = $matchingSlot;
            }  else if($matchingSlot >= $matchingLimit){
                $amount = $matchingLimit;
            }
        }
        return $amount;
    }

    


    public function getMatchingSlotList() {
        $sql = "select point from matching_slot order by point asc";
        $_lh = Yii::app()->db->createCommand($sql)->queryAll();

        if (!empty($_lh)) {
            return $_lh;
            //$v = $_lh[0];
            //echo $v['point'];
        } else {
            return NULL;
        }
    }

    public function getMatchingCalculableMemberList() {
        $criteria = new CDbCriteria();
        $criteria->condition = "status = '1' and active = '1' and parent_id IS NOT NULL ";
        $memberList = Member::model()->findAll($criteria);
        return $memberList;
    }
    
    public function flushAPoint($aPoint, $bPoint){
        $minPoint = $this->getMinPoint($aPoint, $bPoint);
        $newAPoint = $aPoint - $minPoint;
        return $newAPoint;
    }
    
    public function flushBPoint($aPoint, $bPoint){
        $minPoint = $this->getMinPoint($aPoint, $bPoint);
        $newBPoint = $bPoint - $minPoint;
        return $newBPoint;
    }
    
    public function getMinPoint($aPoint , $bPoint){
        $minPoint = 0;
        try {
            if ($aPoint <= $bPoint) {
                $minPoint = $aPoint;
            } else {
                $minPoint = $bPoint;
            }
        } catch (Exception $e) {
            
        }
        return $minPoint;
    }

}
